import {app, BrowserWindow} from 'electron/main'
import http from 'node:http'
import fs from 'node:fs'
import path from 'node:path'
import {fileURLToPath} from 'url';

const port = 80
const __dirname = path.dirname(fileURLToPath(import.meta.url));


// 创建 Node.js HTTP 服务器
const server = http.createServer((req, res) => {
    const filePath = path.join(__dirname, 'dist', req.url === '/' ? 'index.html' : req.url);
    const extname = path.extname(filePath);
    let contentType = 'text/html'; // 默认返回 HTML

    // 根据文件扩展名设置 MIME 类型
    if (extname === '.js') {
        contentType = 'application/javascript';
    } else if (extname === '.css') {
        contentType = 'text/css';
    } else if (extname === '.json') {
        contentType = 'application/json';
    }

    // 读取文件并响应
    fs.readFile(filePath, 'utf-8', (err, data) => {
        if (err) {
            res.writeHead(500, {'Content-Type': 'text/plain'});
            res.end('Error loading file');
            return;
        }

        res.writeHead(200, {'Content-Type': contentType});
        res.end(data);
    });
});

server.listen(port, () => {
    console.log(`Server is running on http://127.0.0.1:${port}`);
});

// 创建 Electron 窗口
let mainWindow;

function createWindow() {
    mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            nodeIntegration: false,  // 禁用 Node.js 集成
            contextIsolation: true,  // 启用上下文隔离
            enableRemoteModule: false,
            preload: path.join(__dirname, '../preload/index.js'),
            sandbox: false
        }
    });

    // 启动 Electron 应用时加载本地网页
    mainWindow.loadURL(`http://127.0.0.1:${port}`).then(r => console.log(r));
    // 打开调试窗口
    mainWindow.webContents.openDevTools();

    //处理serialApi
    serialApiHandle(mainWindow)
}

function serialApiHandle(mainWindow) {

    mainWindow.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => {
        // Add listeners to handle ports being added or removed before the callback for `select-serial-port`
        // is called.
        mainWindow.webContents.session.on('serial-port-added', (event, port) => {
            console.log('serial-port-added FIRED WITH', port)
            // Optionally update portList to add the new port
        })

        mainWindow.webContents.session.on('serial-port-removed', (event, port) => {
            console.log('serial-port-removed FIRED WITH', port)
            // Optionally update portList to remove the port
        })

        event.preventDefault();
        if (portList && portList.length > 0) {
            //默认返回第一个串口id
            callback(portList)
        } else {
            // eslint-disable-next-line n/no-callback-literal
            callback('') // Could not find any matching devices
        }
    })
//授权
    mainWindow.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
        if (permission === 'serial') {
            return true
        }

        return false
    })
//授权
    mainWindow.webContents.session.setDevicePermissionHandler((details) => {
        if (details.deviceType === 'serial') {
            return true
        }

        return false
    })
}


app.whenReady().then(() => {
    createWindow();
});

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});